//
//  ARTLineChartView.m
//  YunDaHome-iOS
//
//  Created by yunda on 2021/9/16.
//  Copyright © 2021 YunDa. All rights reserved.
//

#import "ARTLineChartView.h"
#import "AAGlobalMacro.h"
#import "AAChartKit.h"
#import "PNChart.h"

@interface ARTLineChartView(){
    CGFloat chart_w;
    CGFloat chart_h;
    UIEdgeInsets chart_padding;
}
@property (strong, nonatomic) AAChartView *aaChartView;
@property (strong, nonatomic) PNLineChart *lineChart;

@end

@implementation ARTLineChartView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    [self didInitialize];
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize{
//    self.backgroundColor = [UIColor brownColor];
    
//    self.xLabelArray = @[@"2020-01",@"2020-01",@"2020-01",@"2020-01"];
//    self.yLabelArray = @[@"0",@"20",@"40",@"60"];
//    self.valueArray = @[@(20),@(22),@(33),@(36),@(58),@(54),@(44),@(10),@(20),@(22),@(33),@(36),@(28),@(50),@(33),@(10),@(20),@(22),@(33),@(36),@(58),@(54),@(44),@(10),@(20),@(22),@(33),@(36),@(28),@(50),@(33),@(10),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(22),@(33),@(36),@(58),@(54),@(44),@(10),@(20),@(22),@(33),@(36),@(28),@(50),@(33),@(10),@(20),@(22),@(33),@(36),@(58),@(54),@(44),@(10),@(20),@(22),@(33),@(36),@(28),@(50),@(33),@(10),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(10),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(20),@(22),@(33),@(36),@(58),@(54),@(22),@(33),@(36),@(58),@(54),@(44),@(10)];
    
    chart_padding = UIEdgeInsetsMake(20, 40, 20, 30);
    chart_w = self.qmui_width-chart_padding.left-chart_padding.right;
    chart_h = self.qmui_height-chart_padding.top-chart_padding.bottom;
    _lineColor = [UIColor blackColor];
}

- (void)startDrawing{
    [self drawXYAxis];
    if (self.xLabelArray.count != 0 && self.yLabelArray.count != 0) {
        [self drawGrid];
        if (self.valueArray.count != 0) {
            [self drawValueLine];
        }
    }
}

- (void)startDrawing2{
    if ((self.xLabelArray.count == 0 && self.yLabelArray.count == 0) || self.valueArray.count == 0) {
        return;
    }
    _aaChartView = [[AAChartView alloc]init];
    _aaChartView.frame = J_Frame(chart_padding.left-12, chart_padding.top-10, chart_w+20, chart_h);
    [self addSubview:_aaChartView];
    _aaChartView.userInteractionEnabled = NO;
    [_aaChartView aa_drawChartWithChartModel:[self configureAAChartData]];
    
    [self drawXYAxis];
    [self drawGrid];
}

- (void)startDrawing3{
    if (self.xLabelArray.count != 0 && self.yLabelArray.count != 0) {
        if (self.valueArray.count != 0) {
            [self setupSpoPNChartView];
        }
        [self drawGrid];
    }
    [self drawXYAxis];
}

- (void)startDrawing4{
    if (self.xLabelArray.count != 0 && self.yLabelArray.count != 0) {
        if (self.valueArray.count != 0) {
            [self setupPrPNChartView];
        }
        [self drawGrid];
    }
    [self drawXYAxis];
}

#pragma mark--draw base
// 画x,y轴
- (void)drawXYAxis{
    
    UIBezierPath *path = [UIBezierPath bezierPath];

    [path moveToPoint:CGPointMake(chart_padding.left, chart_padding.top)];
    [path addLineToPoint:CGPointMake(chart_padding.left, chart_padding.top+chart_h)];
    [path addLineToPoint:CGPointMake(chart_padding.left+chart_w, chart_padding.top+chart_h)];
        
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = J_ColorFromHEX(0x000000).CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.5;
    [self.layer addSublayer:layer];
    
    UIBezierPath *path2 = [UIBezierPath bezierPath];

    [path2 moveToPoint:CGPointMake(chart_padding.left+chart_w, chart_padding.top)];
    [path2 addLineToPoint:CGPointMake(chart_padding.left+chart_w, chart_padding.top+chart_h)];
        
    CAShapeLayer *layer2 = [[CAShapeLayer alloc] init];
    layer2.path = path2.CGPath;
    layer2.strokeColor = J_ColorFromHEX(0xCCCCCC).CGColor;
    layer2.fillColor = [UIColor clearColor].CGColor;
    layer2.lineWidth = 0.5;
    [self.layer addSublayer:layer2];
}

- (void)drawGrid{
    UIBezierPath *path = [UIBezierPath bezierPath];
    // 横线
    CGFloat everyY = chart_h/(_yLabelArray.count-1);
    for (int i = 0; i < _yLabelArray.count-1; i ++) {
        [path moveToPoint:CGPointMake(chart_padding.left, chart_padding.top + everyY * i)];
        [path addLineToPoint:CGPointMake(chart_padding.left+chart_w,  chart_padding.top + everyY * i)];
    }
    
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = J_ColorFromHEX(0xCCCCCC).CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.5;
    // 3=线的宽度 1=每条线的间距
//    [layer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3],[NSNumber numberWithInt:1],nil]];
    [self.layer addSublayer:layer];
    
    // 绘制y标签
    for (int i = 0; i < _yLabelArray.count; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:J_FrameWithSize(chart_padding.left, 16)];
        label.center = CGPointMake(label.center.x, chart_padding.top + everyY * i);
        label.textColor = J_ColorFromHEX(0x999999);
        label.textAlignment = NSTextAlignmentCenter;
        label.font = J_Font(10);
        label.adjustsFontSizeToFitWidth = YES;
        label.text = _yLabelArray[_yLabelArray.count-1-i];
        [self addSubview:label];
    }
    
    // 绘制x标签
    CGFloat everyX = chart_w/(_xLabelArray.count);
    for (int i = 0; i < _xLabelArray.count; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(chart_padding.left+everyX*i, chart_padding.top+chart_h, everyX, chart_padding.bottom)];
        label.textColor = J_ColorFromHEX(0x999999);
        if (i ==0) {
            label.textAlignment = NSTextAlignmentLeft;
        }else if (i == _xLabelArray.count-1){
            label.textAlignment = NSTextAlignmentRight;
        }else{
            label.textAlignment = NSTextAlignmentCenter;
        }
        label.font = J_Font(10);
        label.adjustsFontSizeToFitWidth = YES;
        label.text = _xLabelArray[_xLabelArray.count-1-i];
        [self addSubview:label];
    }
}

#pragma mark--自定义chart
// 绘制图表
- (void)drawValueLine{
    
    NSInteger count = _isZhi ? self.valueArray.count : self.valueArray.count-1;
    CGFloat everyX = chart_w/(count);
    CGFloat maxValue = _maxValue,minValue = _minValue;
    CGFloat space = chart_h/(maxValue-minValue);
        
    BOOL isSkip = NO;
    CGPoint lastPoint = CGPointZero;
    UIBezierPath *path = [UIBezierPath bezierPath];
    for (int i = 0; i < self.valueArray.count; i++) {
        
        NSNumber *number = self.valueArray[i];
        CGFloat value = number.floatValue;
        if (value >= maxValue) {
            value = maxValue;
        }
        if (value <= minValue) {
            value = minValue;
        }
        
        CGFloat x = chart_padding.left+i*everyX;
        CGFloat y = chart_padding.top+(maxValue-value)*space;
        
        CGPoint currentPoint = CGPointMake(x,  y);
        if (i == 0) {
            [path moveToPoint:currentPoint];
        }else{
            if (_canSkip == NO) {
                // 连续折线
                if (_isZhi) {
                    [path addLineToPoint:CGPointMake(currentPoint.x, lastPoint.y)];
                }
                [path addLineToPoint:currentPoint];
            }else{
                // 不连续折线
                if (value <= _skip_min || value > _skip_max) {
//                    NSLog(@"跳跃值%@",@(value));
                    isSkip = YES;
                }else{
                    if (isSkip) {
                        [path moveToPoint:currentPoint];
                        isSkip = NO;
                    }else{
                        [path addLineToPoint:currentPoint];
                    }
                }
            }
            
        }
        lastPoint = currentPoint;
    }
    if (_isZhi) {
        [path addLineToPoint:CGPointMake(chart_padding.left+chart_w, lastPoint.y)];
    }
    
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = _lineColor.CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.8;
    [self.layer addSublayer:layer];
    
//    CABasicAnimation *pathAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//    pathAnima.duration = 0.8;
//    pathAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//    pathAnima.fromValue = [NSNumber numberWithFloat:0.0f];
//    pathAnima.toValue = [NSNumber numberWithFloat:1.0f];
//    pathAnima.fillMode = kCAFillModeForwards;
//    pathAnima.removedOnCompletion = NO;
//    [layer addAnimation:pathAnima forKey:@"strokeEndAnimation"];
    _valueArray = @[];
    _xLabelArray = @[];
    _yLabelArray = @[];
}

#pragma mark--AAChart
// 绘制血氧饱和度图
- (AAChartModel *)configureAAChartData{
    return AAChartModel.new
    .animationTypeSet(AAChartAnimationEaseOutCubic)//图形的渲染动画类型为 EaseOutCubic
    .animationDurationSet(@0)//图形渲染动画时长为1200毫秒
    .chartTypeSet(AAChartTypeLine)
    .titleSet(@"")
    .subtitleSet(@"")
    .markerSymbolSet(AAChartSymbolTypeCircle)
    .markerRadiusSet(@0)//设置折线连接点宽度为0,即是隐藏连接点
    .legendEnabledSet(NO)//隐藏图例(底部可点按的小圆点)
    .xAxisVisibleSet(NO)
    .xAxisLabelsEnabledSet(NO)
//    .yAxisGridLineStyleSet([AALineStyle styleWithColor:@"#CCCCCC" dashStyle:@"" width:@0.5])
    .yAxisVisibleSet(NO)
    .yAxisMaxSet(@100)
    .yAxisMinSet(@70)
    .yAxisTickPositionsSet(@[@70,@80,@90,@100])
    .yAxisPlotLinesSet(nil)
    .dataLabelsEnabledSet(NO)
    .seriesSet(@[
        AASeriesElement.new
        .nameSet(@"2")
        .dataSet(self.valueArray)
        .lineWidthSet(@1)
        .zonesSet(@[
            AAZonesElement.new
            .valueSet(@70)
            .colorSet(@"#FFFFFF"),
            AAZonesElement.new
            .valueSet(@88)
            .colorSet(@"#E50C0C"),
            AAZonesElement.new
            .valueSet(@94)
            .colorSet(@"#FF9627"),
            AAZonesElement.new
            .colorSet(@"#222222"),
                  ]),
               ]);
}

#pragma mark--PNChart
- (void)setupSpoPNChartView{
    if (_chartSnapshotLayerImage) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:J_Frame(chart_padding.left, chart_padding.top, chart_w, chart_h)];
        imageView.image = _chartSnapshotLayerImage;
        [self addSubview:imageView];
        return;
    }
    self.lineChart = [[PNLineChart alloc] initWithFrame:J_Frame(chart_padding.left, chart_padding.top, chart_w, chart_h)];
    [self addSubview:self.lineChart];
    
    self.lineChart.showCoordinateAxis = NO;
    self.lineChart.showLabel = NO;
    self.lineChart.showGenYLabels = NO;
    self.lineChart.showYGridLines = NO;
    self.lineChart.thousandsSeparator = YES;
    self.lineChart.yFixedValueMax = 101;
    self.lineChart.yFixedValueMin = 70;
    self.lineChart.yValueMax = 100.1;
    self.lineChart.yValueMin = 70;
    self.lineChart.showSmoothLines = NO;
    self.lineChart.displayAnimated = NO;
    
    [self.lineChart setYLabels:@[
        @"70",
        @"80",
        @"90",
        @"100"
    ]];

    // Line Chart #1
    NSMutableArray *data01Array = [NSMutableArray array];
    NSMutableArray *xLabels = [NSMutableArray array];
    for (NSNumber *number in self.valueArray) {
        [data01Array addObject:number];
        [xLabels addObject:@(0).stringValue];
    }
    self.lineChart.xLabels = xLabels;
    
    PNLineChartData *data01 = [PNLineChartData new];
    data01.color = J_ColorFromHEX(0x222222);
    data01.lineWidth = 0.8;
    data01.rangeColors = @[
//                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(0, 70) color:[UIColor orangeColor]],
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(70, 19) color:J_ColorFromHEX(0xE50C0C)],
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(89, 5) color:J_ColorFromHEX(0xFF9627)],
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(94, 100) color:J_ColorFromHEX(0x222222)]
                           ];
    data01.itemCount = data01Array.count;
    data01.getData = ^(NSUInteger index) {
        CGFloat yValue = [data01Array[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    self.lineChart.chartData = @[data01];
    [self.lineChart.chartData enumerateObjectsUsingBlock:^(PNLineChartData *obj, NSUInteger idx, BOOL *stop) {
        obj.pointLabelColor = [UIColor blackColor];
    }];
    
    [self.lineChart strokeChart];
    
    J_WeakSelf(self)
    [self.lineChart clearData:^(UIImage *chartImage) {
        J_StrongSelf(self)
        self.chartSnapshotLayerImage = chartImage;
        if (self.chartSnapshotCallbeck) {
            self.chartSnapshotCallbeck();
        }
    }];
}

- (void)setupPrPNChartView{
    if (_chartSnapshotLayerImage) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:J_Frame(chart_padding.left, chart_padding.top, chart_w, chart_h)];
        imageView.image = _chartSnapshotLayerImage;
        [self addSubview:imageView];
        return;
    }
    self.lineChart = [[PNLineChart alloc] initWithFrame:J_Frame(chart_padding.left, chart_padding.top, chart_w, chart_h)];
    [self addSubview:self.lineChart];
    
    self.lineChart.showCoordinateAxis = NO;
    self.lineChart.showLabel = NO;
    self.lineChart.showGenYLabels = NO;
    self.lineChart.showYGridLines = NO;
    self.lineChart.thousandsSeparator = YES;
    self.lineChart.yFixedValueMax = 250.1;
    self.lineChart.yFixedValueMin = 0;
    self.lineChart.yValueMax = 250.1;
    self.lineChart.yValueMin = 0;
    self.lineChart.showSmoothLines = NO;
    self.lineChart.displayAnimated = NO;
    
    [self.lineChart setYLabels:@[
        @"0",
        @"50",
        @"100",
        @"150",
        @"200",
        @"250"
    ]];

    // Line Chart #1
    NSMutableArray *data01Array = [NSMutableArray array];
    NSMutableArray *xLabels = [NSMutableArray array];
    for (NSNumber *number in self.valueArray) {
        [data01Array addObject:number];
        [xLabels addObject:@(0).stringValue];
    }
    self.lineChart.xLabels = xLabels;
    
    PNLineChartData *data01 = [PNLineChartData new];
    data01.color = J_ColorFromHEX(0x222222);
    data01.lineWidth = 0.8;
    data01.rangeColors = @[
//                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(0, 70) color:[UIColor orangeColor]],
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(0, 35) color:J_ColorFromHEX(0xE50C0C)],// <=35
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(121, 129) color:J_ColorFromHEX(0xE50C0C)],// >=121
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(36, 23) color:J_ColorFromHEX(0xFF9627)],// >=36 <=59
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(101, 19) color:J_ColorFromHEX(0xFF9627)],// >=101 <=120
                           [[PNLineChartColorRange alloc] initWithRange:NSMakeRange(60, 40) color:J_ColorFromHEX(0x222222)]
                           ];
    data01.itemCount = data01Array.count;
    data01.getData = ^(NSUInteger index) {
        CGFloat yValue = [data01Array[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    self.lineChart.chartData = @[data01];
    [self.lineChart.chartData enumerateObjectsUsingBlock:^(PNLineChartData *obj, NSUInteger idx, BOOL *stop) {
        obj.pointLabelColor = [UIColor blackColor];
    }];
    
    [self.lineChart strokeChart];
    
    J_WeakSelf(self)
    [self.lineChart clearData:^(UIImage *chartImage) {
        J_StrongSelf(self)
        self.chartSnapshotLayerImage = chartImage;
        if (self.chartSnapshotCallbeck) {
            self.chartSnapshotCallbeck();
        }
    }];
}

@end
